<?php
namespace app\admin\controller\setting;

use app\admin\controller\Base;
use app\admin\model\Role;
use app\admin\model\User as ModelUser;

/**
 * 用户管理
 */
class User extends Base
{
    /**
     * 用户列表
     * @auth true
     */
    public function index()
    {
        $this->roles = Role::field('id,name')->select();
        $this->list = ModelUser::like('username')->equal('role_id')->order('id', 'desc')->append(['role'])->paginate(20);
        $this->fetch();
    }

    /**
     * 添加用户
     * @auth true
     */
    public function add()
    {
        if($this->request->isGet()){
            $this->roles = Role::field('id,name')->select();
            $this->fetch('edit');
        }else{
            $data = $this->request->post();
            $model = new ModelUser;
            if(!$model->add($data)){
                $this->jsonFail($model->getError());
            }
            $this->jsonSucc();
        }
    }

    /**
     * 编辑用户
     * @auth true
     */
    public function edit()
    {
        if($this->request->isGet()){
            $this->roles = Role::field('id,name')->select();
            $this->model = ModelUser::find($this->request->param('id'));
            $this->fetch();
        }else{
            $data = $this->request->post();
            $model = new ModelUser;
            if(!$model->edit($data)){
                $this->jsonFail($model->getError());
            }
            $this->jsonSucc();
        }
    }

    /**
     * 删除用户
     * @auth true
     */
    public function delete()
    {
        $id = $this->request->post('id');
        $user = ModelUser::find($id);
        if(!$user){
            $this->jsonFail('用户不存在');
        }
        if($user->id == 10000){
            $this->jsonFail('禁止删除超级管理员');
        }
        if($user->delete()){
            $this->jsonSucc();
        }else{
            $this->jsonFail('删除失败');
        }
    }

    /**
     * 启用/禁用用户
     * @auth true
     */
    public function status()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        $user = ModelUser::find($id);
        if(!in_array($status,[0,1])){
            $this->jsonFail('状态错误');
        }
        $user->status = $status;
        $user->save();
        $this->jsonSucc('操作成功');
    }
}